寫個登入系統吧
建立新的app: userAuth
python manage.py userAuth
settings.py INSTALLED_APPS 加入 userAuth
shop/urls.py
...
path('userAuth/', include('userAuth.urls')),
...
登入+登出的route
userAuth/urls.py
from django.urls import path
from userAuth import views
app_name = 'userAuth'
urlpatterns = [
path('userLogin/', views.userLogin, name='userLogin'),
path('userLogout/', views.userLogout, name='userLogout')
]
authenticate() django 驗證func
login(request, user) 登入func
logout(request) 登出func
userAuth/views.py
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect
from django.urls import reverse
def userLogin(request):
if request.method == 'GET':
return render(request, 'auth/userLogin.html')
elif request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
if not username or not password:
messages.error(request, '請輸入帳號密碼')
return render(request, 'auth/userLogin.html')
user = authenticate(request, username=username, password=password)
if not user:
messages.error(request, '登入失敗')
return render(request, 'auth/userLogin.html')
# user
login(request, user)
messages.error(request, '登入成功')
return redirect(reverse('main:main'))
def userLogout(request):
logout(request)
messages.error(request, '登出成功')
return redirect(reverse('main:main'))
userAuth/templates/userAuth/userLogin.html
{% extends 'main/base.html' %}
{% block content %}
<h2>登入</h2>
<form method="post" action="{% url 'userAuth:userLogin' %}">
{% csrf_token %}
<p>
<label for="username">帳號:</label>
<input id="username" type="text" name="username">
</p>
<p>
<label for="password">密碼:</label>
<input id="password" type="password" name="password">
</p>
<input type="submit" value="登入">
</form>
{% endblock %}
加上登入與登出的連結
{{ user }} 是預設就會傳的範本變數
user.is_authenticated 回傳True 或 False 是否驗證
main/templates/main/nav.html
...
<li class="nav-item active">
{% if not user.is_authenticated %}
<a class="nav-link" href="{% url 'userAuth:userLogin' %}">登入</a>
{% else %}
<a class="nav-link" href="{% url 'userAuth:userLogout' %}">登出</a>
{% endif %}
</li>
...
就完成了